<?php
class EasyList extends Vector {
  public $sql = "SELECT SQL_CALC_FOUND_ROWS * FROM `::1` ";
  public $num = 0;
  public $page = 1;
  public $table = 'content';
  /**
   * template for list
   * @var Template $template
   */
  public $template;
  public $type = "Atom";
  public $before_output;
  public $order = '';
  public $rows_overall;
  
  protected $items = array();
  
  public function __construct( $table = '' ) {
    !empty($table) && $this->table = $table;
  }
  
  public function load( $q = null ) {
    $this->page = $this->page+0 ? $this->page+0 : 1;
    $sql = $q !== null ? $q : $this->sql;
    if ( $this->order ) {
      $sql .= " ORDER BY ".$this->order;
    }
    if ( $this->num ) {
      $sql .= " LIMIT ".(($this->page - 1) * $this->num).",".$this->num;
    }
    $res = db::q( $sql, $this->table );
    $i = 0; $this->item = array();
    while ( $r = $res->assoc() ) {
      $this->item[$i] = new $this->type( $r );
      if ( is_a( $this->item[$i], 'Atom' )) {
        if ( $this->template !== null ) {
          $this->item[$i]->template = $this->template;
        }
        $i++;
      }
      else
        unset( $this->item[$i] );
    }
    $this->rows_overall = db::q("SELECT FOUND_ROWS() AS `num`")->get('num');
  }
  
  
  /**
   * Get html code
   * @return Template
   */
  public function get_html( $var_name='elem' ) {
    if ( !empty($this->template) ) {
      $html = is_a($this->template, 'Template') ? $this->template : new Template($this->template);
      foreach ( $this->item as &$elem ) {
        if ( is_a( $elem, 'Atom' ) ) {
          $html->add( $var_name, $elem );
        }
      }
    } else {
      $html = new Template('empty');
    }
    return $html;
  }
  
    
  /**
   * Concat html code of elements
   * @return Template
   */
  public function concat( $template=null, $var_name='elem' ) {
    $html = '';
    $i = 0;
    if ( $this->num() && !empty($template) ) {
      foreach ( $this->item as &$elem ) {
        if ( is_a( $elem, 'Atom' ) ) {
          if ( $template ) {
            $elem->template = clone $template;
          }
          $html .= $elem->get_html( $var_name )->assign('k',$i++);
        } else {
          $html .= $elem;
        }
      }
    } else {
      $html = new Template('empty');
    }
    return $html;
  }
  
  
  /**
   * Get item at $index
   * @param $index int
   * @return ListElement
   */
  public function &at( $index ) {
    if ( array_key_exists( $index, $this->item ) ) {
      return $this->item[$index];
    }
    return $tmp = null;
  }
  
  public function num() {
    return count($this->item);
  }
  
  function page_nav( ) {
    $this->template->assign( 'page',  $this->page );
    $this->template->assign( 'pages', ceil ( $this->rows_overall / $this->num) );
  }
}



